package com.nba.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.nba.common.exception.CustomException;
import com.nba.common.controller.BaseController;
import com.nba.common.dao.IJdbcDao;
import com.nba.common.framework.ErrorCode;
import com.nba.common.framework.UserSessionData;
import com.nba.common.utils.Environment;
import com.nba.common.utils.FileUtils;
import com.nba.common.web.httpobjects.MsgResult;

@Controller
@RequestMapping(value="/")
public class FileUploadController extends BaseController{

	@Autowired
	private IJdbcDao jdbcDao;
	
	/**
     * pic文件上传
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/upload/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public MsgResult uploadImg(HttpServletRequest request,
            HttpServletResponse response) throws CustomException {
    	UserSessionData user = (UserSessionData) request.getSession().getAttribute(Environment.SESSION_USER_LOGIN_INFO);
        Map<String, Object> map = new HashMap<String, Object>();
        if(user!= null) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("imgFile");
            String fileName = file.getOriginalFilename();
            Long filesize = file.getSize();
            String fileext = "";
            Map<String,Object> fmap = null;//保存file以后返回的map
            if(fileName.lastIndexOf(".")!=-1){
                fileext=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                if(!Environment.IMG_SUFFIX.contains(fileext)){
                    //message = "上传图片格式不正确，"+"目前只支持 " + Environment.IMG_SUFFIX+" 类型文件上传!";
                    //flag = false;
                	throw new CustomException(ErrorCode.PIC_SUFFIX_ERROR);
                }else{
                    Long maxlen=10*1024*1024l;
                    Long customlen=Environment.IMG_FILE_SIZE*1024l;
                    if((filesize)<(maxlen)){
                        if((filesize)<=(customlen)){
                            fmap = FileUtils.saveImg(file, request, true);
                            if((Integer)fmap.get("success") == 1){
                                //插入附件表
                                String insertSql = "insert into accessory_file (id, addTime, is_del, ext, width, height, info, name, path, size, user_id) " +
                                                                         "values(?, now(),   ?,        ?,      ?,     ?,    ?,    ?,    ?,    ?,       ?)";
                                jdbcDao.execute(insertSql, 
                                        new Object[]{fmap.get("fileName"), "N", fileext, (Integer)fmap.get("width"), (Integer)fmap.get("height"), "", 
                                        fileName, Environment.IMG_SEC_PATH, filesize, user.getUserId()});
                            }else{
                            	throw new CustomException(ErrorCode.FILE_SAVE_ERROR);
                            }
                        }else{
                            //文件超过规定范围
                            //message = "文件大小超出限制！";
                            throw new CustomException(ErrorCode.FILE_SIZE_OVERFLOW);
                        }
                    }else{
                        //文件超过2M会裁图失败
                        //flag =false;
                        //message = "文件大小超出限制！";
                        throw new CustomException(ErrorCode.FILE_SIZE_OVERFLOW);
                    }
                }
            }else{
                //flag =false;
                //message = "请检查文件是正确！";
                throw new CustomException(ErrorCode.FILE_NAME_ERROR);
            }  
            map.put("id", fmap.get("fileName"));
            map.put("filePath", Environment.FILE_SEC_PATH);
            map.put("fileExt", fileext);
            map.put("url", request.getContextPath()+Environment.IMG_SEC_PATH + fmap.get("fileName")+"."+fileext);
            return new MsgResult(map);
        }else{
        	throw new CustomException(ErrorCode.NO_LOGIN);
        }
    }
	
    /**
     * 文件上传
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public MsgResult FileUpload(HttpServletRequest request,
            HttpServletResponse response) throws CustomException {
    	UserSessionData user = (UserSessionData) request.getSession().getAttribute(Environment.SESSION_USER_LOGIN_INFO);
        Map<String, Object> map = new HashMap<String, Object>();
        if(user!= null) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadFile");
            String fileName = file.getOriginalFilename();
            Long filesize = file.getSize();
            String fileext = "";
            Map<String,Object> fmap = null;//保存file以后返回的map
            if(fileName.lastIndexOf(".")!=-1){
                fileext=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                {
                    Long maxlen=Environment.FILE_SIZE*1024l;
                    if((filesize)<(maxlen)){
                        fmap = FileUtils.saveFile(file, request);
                        if((Integer)fmap.get("success") == 1){
                            //插入附件表
                            String insertSql = "insert into accessory_file (id, addTime, is_del, ext, info, name, path, size, rela_id, user_id) " +
                                    "values(?, now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                            jdbcDao.execute(insertSql, 
                                    new Object[]{fmap.get("fileName"), "N", fileext, "", fileName, Environment.FILE_SEC_PATH, filesize, "", user.getUserId()});
                        }else{
                            throw new CustomException(ErrorCode.FILE_SAVE_ERROR);
                        }
                    }else{
                        //文件超过2M会裁图失败
                        //flag =false;
                        //message = "文件大小超出限制！";
                    	throw new CustomException(ErrorCode.FILE_SIZE_OVERFLOW);
                    }
                }
            }else{
                //message = "请检查文件是正确！";
                throw new CustomException(ErrorCode.FILE_NAME_ERROR);
            }  
            map.put("id", fmap.get("fileName"));//文件名称
            map.put("filePath", Environment.FILE_SEC_PATH);
            map.put("fileExt", fileext);
            map.put("url", request.getContextPath()+Environment.FILE_SEC_PATH + fmap.get("fileName")+"."+fileext);
            return new MsgResult(map);
        }else{
        	throw new CustomException(ErrorCode.NO_LOGIN);
        }
    }
}
